package com.yinhai.activity;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BaiduMap.OnMarkerDragListener;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.MyLocationConfiguration.LocationMode;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.search.core.SearchResult;
import com.baidu.mapapi.search.geocode.GeoCodeResult;
import com.baidu.mapapi.search.geocode.GeoCoder;
import com.baidu.mapapi.search.geocode.OnGetGeoCoderResultListener;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeOption;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeResult;
import com.yinhai.photo.utils.Photo;

/**
 * 此demo用来展示如何结合定位SDK实现定位，并使用MyLocationOverlay绘制定位位置 同时展示如何使用自定义图标绘制并点击时弹出泡泡
 * 
 */
public class PosLocation extends Activity implements
		OnGetGeoCoderResultListener {

	// 定位相关
	LocationClient mLocClient;
	public MyLocationListenner myListener = new MyLocationListenner();
	private LocationMode mCurrentMode;
	BitmapDescriptor mCurrentMarker;

	MapView mMapView;
	BaiduMap mBaiduMap;

	// UI相关
	OnCheckedChangeListener radioButtonListener;
	Button requestLocButton;
	boolean isFirstLoc = true;// 是否首次定位
	LatLng locPoint;
	String myaddress = "";

	private Intent mIntent;
	private int mLatitude;
	private int mLongitude;

	private Button pos_bt;
	private Button pos_cancel;

	Marker marker;

	GeoCoder mSearch = null;
	LatLng p;
	View map_tt;
	TextView map_bubbleText;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.pos_location);

		pos_bt = (Button) findViewById(R.id.pos_bt);
		pos_cancel = (Button) findViewById(R.id.pos_cancel);

		pos_bt.setEnabled(false);

		pos_bt.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				// Toast.makeText(PosLocation.this,
				// "纬度："+locPoint.latitude+"纬度："+locPoint.longitude+"\n地址："+myaddress,Toast.LENGTH_SHORT).show();
				// TODO Auto-generated method stub
				/*
				 * if(!desText.getText().equals("") &&
				 * !desText.getText().equals(lost_tips)){ //int lal =
				 * locPoint.getLatitudeE6(); //int loc =
				 * locPoint.getLongitudeE6();
				 * //Toast.makeText(LocationActivity.this,
				 * pos+"--"+locPoint.getLatitudeE6
				 * ()+","+locPoint.getLongitudeE6(), Toast.LENGTH_LONG).show();
				 * Intent mIntent = new Intent("com.im.sendpos");
				 * mIntent.putExtra("address", myaddress);
				 * mIntent.putExtra("latitude", ); mIntent.putExtra("longitude",
				 * ); PosLocation.this.sendBroadcast(mIntent); finish(); }
				 */

				mMapView.getMap().snapshot(
						new BaiduMap.SnapshotReadyCallback() {

							@Override
							public void onSnapshotReady(Bitmap arg0) {
								Intent mIntent = new Intent("com.im.sendpos");
								mIntent.putExtra("address", myaddress);
								mIntent.putExtra("latitude",
										String.valueOf(locPoint.latitude));
								mIntent.putExtra("longitude",
										String.valueOf(locPoint.longitude));
								mIntent.putExtra("uuid", getIntent()
										.getStringExtra("uuid"));
								Photo.saveBitmap(
										getIntent().getStringExtra("uuid"),
										Photo.zoomImg(arg0, 128,
												PosLocation.this));
								PosLocation.this.sendBroadcast(mIntent);
								finish();
							}
						});

			}
		});
		pos_cancel.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				// TODO Auto-generated method stub
				finish();
			}
		});

		LayoutInflater inflater = LayoutInflater.from(PosLocation.this);
		View view = inflater.inflate(R.layout.pos_tips, null);
		map_tt = view.findViewById(R.id.map_tt);
		map_bubbleText = (TextView) view.findViewById(R.id.map_bubbleText);

		mCurrentMode = LocationMode.NORMAL;

		// 地图初始化
		mMapView = (MapView) findViewById(R.id.bmapView);
		mBaiduMap = mMapView.getMap();

		mSearch = GeoCoder.newInstance();
		mSearch.setOnGetGeoCodeResultListener(this);
		/*
		 * mIntent = getIntent(); mLatitude = mIntent.getIntExtra("latitude",
		 * 0); mLongitude = mIntent.getIntExtra("longitude", 0);
		 * 
		 * if (mLatitude != 0 && mLongitude != 0) { locPoint= new
		 * LatLng(39.963175, 116.400244); }
		 */
		// locPoint= new LatLng(39.963175, 116.400244);
		//
		// setCenter(locPoint);
		// 定义坐标

		// 添加标注

		mBaiduMap.setOnMarkerDragListener(new OnMarkerDragListener() {
			public void onMarkerDrag(Marker marker) {

			}

			public void onMarkerDragEnd(Marker marker) {
				// Toast.makeText(LocationDemo.this,"当前位置：" +
				// marker.getPosition().latitude + ", "+
				// marker.getPosition().longitude,Toast.LENGTH_SHORT).show();
				mSearch.reverseGeoCode(new ReverseGeoCodeOption()
						.location(marker.getPosition()));
				locPoint = marker.getPosition();

				pos_bt.setEnabled(true);
				// setCenter(marker.getPosition());
				// setCenter(marker);
			}

			public void onMarkerDragStart(Marker marker) {
				// Toast.makeText(LocationDemo.this, "开始拖拽...",
				// Toast.LENGTH_LONG).show();
				pos_bt.setEnabled(false);
			}
		});

		mBaiduMap.setMapType(BaiduMap.MAP_TYPE_NORMAL);

		// 开启定位图层
		mBaiduMap.setMyLocationEnabled(true);
		// 定位初始化
		mLocClient = new LocationClient(this);
		mLocClient.registerLocationListener(myListener);
		LocationClientOption option = new LocationClientOption();
		option.setOpenGps(true); // 打开gps
		option.setCoorType("bd09ll"); // 设置坐标类型，总共有几个类型具体的可以查看百度文档说明
		option.setScanSpan(1000); // 设置定位间隔时间
		option.setAddrType("all"); // 设置返回类型，all = 表示返回所有的数据
		option.setPriority(LocationClientOption.NetWorkFirst);
		mLocClient.setLocOption(option);
		mLocClient.start();
	}

	/**
	 * 定位SDK监听函数
	 */
	public class MyLocationListenner implements BDLocationListener {

		@Override
		public void onReceiveLocation(BDLocation location) {
			// map view 销毁后不在处理新接收的位置
			if (location == null || mMapView == null) {
				return;
			} else {
				if (isFirstLoc) {
					locPoint = new LatLng(location.getLatitude(),
							location.getLongitude());

					myaddress = location.getAddrStr();
					map_bubbleText.setText(myaddress);
					// Toast.makeText(LocationDemo.this,
					// myaddress,Toast.LENGTH_SHORT).show();
					isFirstLoc = false;
					// BitmapDescriptor bitmap =
					// BitmapDescriptorFactory.fromResource(R.drawable.icon_marka);

					setCenter(locPoint);
					pos_bt.setEnabled(true);
				}
			}

			/*
			 * MyLocationData locData = new MyLocationData.Builder()
			 * .accuracy(location.getRadius()) // 此处设置开发者获取到的方向信息，顺时针0-360
			 * .direction(100).latitude(location.getLatitude())
			 * .longitude(location.getLongitude()).build();
			 * mBaiduMap.setMyLocationData(locData); if (isFirstLoc) {
			 * isFirstLoc = false; LatLng ll = new
			 * LatLng(location.getLatitude(), location.getLongitude());
			 * MapStatusUpdate u = MapStatusUpdateFactory.newLatLng(ll);
			 * mBaiduMap.animateMapStatus(u); }
			 */

		}

		public void onReceivePoi(BDLocation poiLocation) {
		}
	}

	public void setCenter(LatLng ll) {
		mBaiduMap.clear();
		// mBaiduMap.notify();
		BitmapDescriptor bitmap = BitmapDescriptorFactory.fromView(map_tt);
		OverlayOptions options = new MarkerOptions().position(ll) // 设置marker的位置
				.icon(bitmap) // 设置marker图标
				.zIndex(18) // 设置marker所在层级
				.draggable(true); // 设置手势拖拽

		// 在地图上添加Marker，并显示
		// mBaiduMap.addOverlay(options);

		marker = (Marker) mBaiduMap.addOverlay(options);

		MapStatus mMapStatus = new MapStatus.Builder()
				.target(marker.getPosition()).zoom(18).build();
		// 定义MapStatusUpdate对象，以便描述地图状态将要发生的变化
		MapStatusUpdate mMapStatusUpdate = MapStatusUpdateFactory
				.newMapStatus(mMapStatus);
		// 改变地图状态
		mBaiduMap.animateMapStatus(mMapStatusUpdate);
		// mMapView.refreshDrawableState();

	}

	private Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 0:
				if (null == locPoint)
					return;

				break;
			case 1:
				setCenter(locPoint);
				pos_bt.setEnabled(true);
				break;
			}
		}
	};

	@Override
	protected void onPause() {
		mMapView.onPause();
		super.onPause();
	}

	@Override
	protected void onResume() {
		mMapView.onResume();
		super.onResume();
	}

	@Override
	protected void onDestroy() {
		// 退出时销毁定位
		mLocClient.stop();
		// 关闭定位图层
		mBaiduMap.setMyLocationEnabled(false);
		mMapView.onDestroy();
		mSearch.destroy();
		mMapView = null;
		super.onDestroy();
	}

	@Override
	public void onGetGeoCodeResult(GeoCodeResult arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onGetReverseGeoCodeResult(ReverseGeoCodeResult result) {
		// TODO Auto-generated method stub
		if (result == null || result.error != SearchResult.ERRORNO.NO_ERROR) {
			Toast.makeText(PosLocation.this, "抱歉，未能找到结果", Toast.LENGTH_SHORT)
					.show();
			return;
		} else {
			myaddress = result.getAddress();
			map_bubbleText.setText(myaddress);
			Message msg = new Message();
			msg.what = 1;
			mHandler.sendMessage(msg);
			// Toast.makeText(LocationDemo.this,
			// myaddress,Toast.LENGTH_SHORT).show();
		}
	}

}
